<template>
  <div class="course-goal-relation-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>课程目标与毕业要求的关系</span>
        </div>
      </template>
      
      <CourseChoose :courseInfo="courseInfo || null" @course-selected="onCourseSelected" />
      
      <div v-if="selectedCourse" class="relation-section">
        <el-divider content-position="left">课程目标与毕业要求关系</el-divider>
        
        <div v-for="(relation, idx) in relations" :key="relation.id" class="relation-item">
          <el-card class="relation-card">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="课程目标" required>
                  <el-input 
                    v-model="relation.course_goal" 
                    placeholder="请输入课程目标"
                    type="textarea"
                    :rows="2"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="毕业要求" required>
                  <el-select 
                    v-model="relation.graduation_requirement_id" 
                    placeholder="请选择毕业要求"
                    style="width: 100%;"
                    @change="onGraduationRequirementChange(idx)"
                  >
                    <el-option
                      v-for="req in graduationRequirements"
                      :key="req.id"
                      :label="`${req.id} ${req.name}`"
                      :value="req.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="指标点" required>
                  <el-select 
                    v-model="relation.index_id" 
                    placeholder="请选择指标点"
                    style="width: 100%;"
                    :disabled="!relation.graduation_requirement_id"
                  >
                                         <el-option
                       v-for="point in getIndexesByRequirement(relation.graduation_requirement_id)"
                       :key="point.indexId"
                       :label="`${point.indexId} ${point.indexDesc || point.desc || ''}`"
                       :value="point.indexId"
                     />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支撑度" required>
                  <el-select v-model="relation.support_level" placeholder="请选择支撑度" style="width: 100%;">
                    <el-option label="高（H）" value="H" />
                    <el-option label="中（M）" value="M" />
                    <el-option label="低（L）" value="L" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item>
              <el-button type="danger" @click="removeRelation(idx)" size="small">
                删除关系
              </el-button>
            </el-form-item>
          </el-card>
        </div>
        
        <el-form-item>
          <el-button type="primary" @click="addRelation">
            添加关系
          </el-button>
          <el-button type="success" @click="saveRelations" :loading="saving">
            保存
          </el-button>
          <el-button type="warning" @click="handleNext">
            下一项
          </el-button>
        </el-form-item>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import CourseChoose from './CourseChoose.vue'
import { courseApi } from '@/api/courseApi.js'

// 定义props
const props = defineProps({
  courseInfo: {
    type: Object,
    default: null
  }
})

// 定义emits
const emit = defineEmits(['next-step'])

// 响应式数据
const selectedCourse = ref(null)
const relations = ref([])
const graduationRequirements = ref([])
const saving = ref(false)

// 课程选择事件处理
const onCourseSelected = async (course) => {
  console.log('CourseGoalRelation onCourseSelected:', { course })
  selectedCourse.value = course
  // console.log('接收到的课程数据:', course)
  
  // 使用后端返回的graduationRequirements数据
  if (course.graduationRequirements && Array.isArray(course.graduationRequirements)) {
    graduationRequirements.value = course.graduationRequirements
    // console.log('毕业要求数据:', graduationRequirements.value)
  } else {
    graduationRequirements.value = []
    ElMessage.warning('未找到毕业要求数据')
  }
  
  // 清空之前的关系数据
  relations.value = []
  
  // 查询该课程的现有关系数据
  try {
    const result = await courseApi.queryCourseGoalRelation(course.id)
    const goalRelations = result.data || result || []
    
    if (goalRelations.length > 0) {
      // 将后端数据转换为前端格式
      relations.value = goalRelations.map((relation, index) => ({
        id: Date.now() + index + Math.random(),
        course_goal: relation.course_goal || '',
        graduation_requirement_id: relation.graduation_requirement || '',
        index_id: relation.graduation_index || '',
        support_level: relation.support_degree || 'H'
      }))
      
      ElMessage.success(`已加载 ${goalRelations.length} 条现有关系数据`)
    } else {
      ElMessage.info('该课程暂无课程目标与毕业要求的关系数据')
    }
  } catch (error) {
    console.error('查询课程关系数据失败:', error)
    ElMessage.warning('查询现有关系数据失败，请手动添加')
  }
}

// 监听props变化，如果有课程信息则自动选择
watch(() => props.courseInfo, (newCourseInfo) => {
  console.log('CourseGoalRelation watch courseInfo:', { newCourseInfo })
  if (newCourseInfo && Object.keys(newCourseInfo).length > 0 && newCourseInfo.id) {
    onCourseSelected(newCourseInfo)
  } else {
    // 如果没有有效的课程信息，清空状态
    selectedCourse.value = null
    relations.value = []
    graduationRequirements.value = []
  }
}, { immediate: true })

// 添加关系
const addRelation = () => {
  relations.value.push({
    id: Date.now() + Math.random(),
    course_goal: '',
    graduation_requirement_id: '',
    index_id: '',
    support_level: 'H'
  })
}

// 删除关系
const removeRelation = (idx) => {
  relations.value.splice(idx, 1)
}

// 毕业要求变化时清空指标点选择
const onGraduationRequirementChange = (idx) => {
  relations.value[idx].index_id = ''
}

// 根据毕业要求ID获取指标点列表
const getIndexesByRequirement = (reqId) => {
  const req = graduationRequirements.value.find(r => r.id === reqId)
  return req && req.indexPoints ? req.indexPoints : []
}

// 保存关系
const saveRelations = async () => {
  if (relations.value.length === 0) {
    ElMessage.warning('请至少添加一个关系')
    return
  }
  
  // 验证必填字段
  for (let i = 0; i < relations.value.length; i++) {
    const relation = relations.value[i]
    if (!relation.course_goal.trim()) {
      ElMessage.error(`第${i + 1}行的课程目标不能为空`)
      return
    }
    if (!relation.graduation_requirement_id) {
      ElMessage.error(`第${i + 1}行的毕业要求不能为空`)
      return
    }
    if (!relation.index_id) {
      ElMessage.error(`第${i + 1}行的指标点不能为空`)
      return
    }
    if (!relation.support_level) {
      ElMessage.error(`第${i + 1}行的支撑度不能为空`)
      return
    }
  }
  
  saving.value = true
  
  try {
    // 转换数据格式以匹配API要求
    const goal_relation = relations.value.map(relation => ({
      course_goal: relation.course_goal.trim(),
      graduation_requirement: relation.graduation_requirement_id,
      graduation_index: relation.index_id,
      support_degree: relation.support_level
    }))
    
    const saveData = {
      courseId: selectedCourse.value.id,
      goal_relation: goal_relation
    }
    
    console.log('保存数据:', saveData)
    
    // 调用实际的保存API
    const result = await courseApi.saveCourseGoalRelation(saveData)
    
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请检查网络连接或联系管理员')
  } finally {
    saving.value = false
  }
}

// 跳转到下一项（不保存）
const handleNext = () => {
  console.log('CourseGoalRelation handleNext:', { selectedCourse: selectedCourse.value })
  
  // 检查是否有选中的课程
  if (!selectedCourse.value || !selectedCourse.value.id) {
    ElMessage.warning('请先选择课程')
    return
  }
  
  // 构建要传递的课程信息，包含自动查询所需的参数
  const courseInfo = {
    ...selectedCourse.value,
    grade: selectedCourse.value.grade || selectedCourse.value.year,
    major: selectedCourse.value.major || selectedCourse.value.majorName,
    courseId: selectedCourse.value.courseId || selectedCourse.value.id,
    courseName: selectedCourse.value.courseName || selectedCourse.value.name
  }
  
  // 触发下一项事件
  emit('next-step', 'course-4', courseInfo)
}
</script>

<style scoped>
.course-goal-relation-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.relation-section {
  margin-top: 20px;
}

.relation-item {
  margin-bottom: 20px;
}

.relation-card {
  margin-bottom: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
</style>